package com.taoyibao.hongcanting.ui.home.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityNoSlidePresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.ApiConstant;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.event.EventQRCode;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.DeskModel;
import com.taoyibao.hongcanting.model.SanFangBaseModel;
import com.taoyibao.hongcanting.ui.home.delegate.QRCodedelagate;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.DataUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.net.URLDecoder;
import java.util.Set;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

/**
 * @author TangAnna
 * @description: 扫描二维码页面
 * @date :${DATA} 9:59
 */
public class QRCodeActivity extends BaseActivityNoSlidePresenter<QRCodedelagate> implements QRCodeView.Delegate {
    public ZXingView mZXingView;

    @Override
    protected Class<QRCodedelagate> getDelegateClass() {
        return QRCodedelagate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        mZXingView = viewDelegate.get(R.id.zxing);
        mZXingView.setDelegate(this);
        mZXingView.startCamera();
        mZXingView.startSpot();
    }

    /**
     * @param context
     * @param source  来源
     */
    public static void open(Context context, String source) {
        Intent intent = new Intent(context, QRCodeActivity.class);
        intent.putExtra(CodeConstant.ACTIVITY_SOURCE, source);
        context.startActivity(intent);
    }


    /**
     * 获取桌位号
     */
    public void getDeskId(String id) {
        JsonApiWrapper.getApiService().getDeskQr(ApiConstant.MASTER_ID, DataUtils.getKey(), id)
                .compose(new DefaultTransformer<SanFangBaseModel<DeskModel>>())
                .subscribe(new ProgressSubscriber<SanFangBaseModel<DeskModel>>(this, true) {
                    @Override
                    public void onNext(SanFangBaseModel<DeskModel> deskModelSanFangBaseModel) {
                        if (deskModelSanFangBaseModel.Code == NetCode.HTTP_200 && deskModelSanFangBaseModel.Data != null) {
                            next(deskModelSanFangBaseModel.Data.desk_id, deskModelSanFangBaseModel.Data.desk_name);
                        } else {
                            super.onNext(deskModelSanFangBaseModel);
                        }

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mZXingView.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mZXingView.stopCamera();
    }

    /**
     * 扫描成功
     *
     * @param result
     */
    @Override
    public void onScanQRCodeSuccess(String result) {
        LogUtils.dNormal("识别的二维码result", result);
        String decode = URLDecoder.decode(result);
        LogUtils.dNormal("识别的二维码decode", decode);
        Uri uri = Uri.parse(decode);
        //获取Id值
        String id = null;
        Set<String> names = uri.getQueryParameterNames();
        for (String name : names) {
            LogUtils.dNormal("识别的二维码 name：", name);
//            String parameter = uri.getQueryParameter(name);
            LogUtils.dNormal("识别的二维码 parameter：", uri.getQueryParameter(name));

            if (TextUtils.equals(name, "page")) {//TODO 第一版本取出id的方法
                String parameter = uri.getQueryParameter(name);
                id = parameter.split("id=")[1];
            } else if (TextUtils.equals(name, "ID")) {
                id = uri.getQueryParameter(name);
            }
        }
        if (TextUtils.isEmpty(id)) {//先判断是否是有ID参数
            mZXingView.stopSpot();
            mZXingView.startSpot();
            ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintOperationFailedQRFail));
        } else {
            mZXingView.stopSpot();
            getDeskId(id);
        }
    }

    /**
     * 页面跳转
     *
     * @param deskId
     * @param deskName
     */
    public void next(String deskId, String deskName) {
        if (!TextUtils.isEmpty(deskId)) {
            //保存座位ID
            SpUtils.putSeatId(deskId);
            SpUtils.putSeatName(deskName);
            NumberPeopleActivity.open(this, getIntent().getStringExtra(CodeConstant.ACTIVITY_SOURCE));
            sendEvent();
            finish();
        }
    }

    /**
     * 发送消息更新需要变化桌位的位置
     */
    public void sendEvent() {
        EventQRCode eventQRCode = new EventQRCode();
        eventQRCode.seatId = SpUtils.getSeatId();
        eventQRCode.seatName = SpUtils.getSeatName();
        EventBus.getDefault().post(eventQRCode);
    }

    /**
     * 当前环境变化
     *
     * @param isDark 是否变暗
     */
    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    /**
     * 相机打开错误
     */
    @Override
    public void onScanQRCodeOpenCameraError() {
        ToastUtils.showToast("相机打开错误");
    }


}
